// jwt的key
const secret_key = 'lihklihk';

const jwt = require('jsonwebtoken');

function generateToken (user) {
  return jwt.sign(user, secret_key);
}

function verifyToken (req, res, next) {
  const token = req.headers['authorization'];

  if (!token) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  jwt.verify(token, secret_key, (err, decoded) => {
    if (err) {
      return res.status(401).json({ error: 'Invalid token' });
    }

    req.user = decoded;
    next();
  });
}

module.exports = {
  generateToken,
  verifyToken
};